/** 附件上传 */

import {Form, Button, message} from 'antd'
import React, {forwardRef, useState, useRef} from 'react'
import {
	ActionType,
	EditableFormInstance,
	ProColumns,
	EditableProTable,
} from '@ant-design/pro-components'
import {PlusOutlined} from '@ant-design/icons'
import {getPublicDownloadUrl} from '@/service/common/upload'
import styles from './index.less'
import CustomUpload from '@/components/Upload'
import {DataSourceType} from '../data.t'

type PropsType = {
	type: string
	attachmentData: readonly DataSourceType[]
	setAttachmentData: React.Dispatch<
		React.SetStateAction<readonly DataSourceType[]>
	>
}

const attachmentTable = (props: PropsType) => {
	const {type, attachmentData, setAttachmentData} = props
	const [form] = Form.useForm()
	const actionRef = useRef<ActionType>()
	const editorFormRef = useRef<EditableFormInstance<DataSourceType>>()
	const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([])
	const [attachment, setAttachment] = useState<any>({})

	const uploadDom = (targetAttr: number) => {
		const uploadProps: any = {
			key: targetAttr,
			modelName: 'assetInventoryPlan',
			targetAttr,
			uploadType: 'devUpload',
			all: true,
			isImage: false,
			callback: (key: any) => {
				if (key?.id) {
					getPublicDownloadUrl([key.id]).then((result: any) => {
						setAttachment(result?.data?.[0])
					})
				} else {
					setAttachment({})
				}
			},
		}
		return (
			<>
				<CustomUpload {...uploadProps} />
			</>
		)
	}
	const attachmentColumns: ProColumns<DataSourceType>[] = [
		{
			title: 'No',
			dataIndex: 'index',
			valueType: 'index',
			width: 80,
			readonly: true,
			align: 'center',
		},
		{
			title: '附件名称',
			key: 'name',
			dataIndex: 'name',
			align: 'center',
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '附件示例',
			key: 'urlName',
			dataIndex: 'urlName',
			tip: '附件说明：附件最大支持20M，支持格式：PDF、Word、Excel、ZIP、RAR',
			align: 'center',
			formItemProps: {
				rules: [
					{
						required: Object?.keys(attachment)?.length === 0,
						message: '此项为必填项',
					},
				],
			},
			renderFormItem: () => uploadDom(attachmentData?.length),
			render: (text, record) => <a href={record?.href}>{text}</a>,
		},
		{
			title: '操作',
			valueType: 'option',
			width: 120,
			align: 'center',
			hideInTable: type === 'view' || type === 'process',
			render: (text, record) => [
				<Button
					type="link"
					key="delete"
					onClick={() => {
						setAttachmentData(
							attachmentData.filter(
								(item: {url: string | number}) =>
									item.url !== record.url,
							),
						)
					}}>
					删除
				</Button>,
			],
		},
	]

	return (
		<div className={styles.addPlan}>
			{type !== 'view' && type !== 'process' ? (
				<>
					<p className={styles.promptText}>
						请上传示例附件！此附件主体需要填写并上传中台统一收集汇总！
					</p>
					<Button
						icon={<PlusOutlined />}
						type="primary"
						ghost
						size="small"
						style={{marginBottom: '12px'}}
						onClick={() => {
							actionRef.current?.addEditRecord?.({
								id: (Math.random() * 1000000).toFixed(0),
							})
						}}>
						新增
					</Button>
				</>
			) : (
				''
			)}
			<EditableProTable<DataSourceType>
				className={styles.attachmentTable}
				bordered
				rowKey="id"
				actionRef={actionRef}
				editableFormRef={editorFormRef}
				recordCreatorProps={false}
				columns={attachmentColumns}
				value={attachmentData}
				editable={{
					form,
					editableKeys,
					onSave: async (rowKey, data) => {
						const newData = {
							...data,
							urlName: attachment?.filename,
							herf: attachment?.url,
							url: attachment?.id,
						}
						if (Object?.keys(attachment)?.length) {
							const newAttachmentData = [...attachmentData]
							newAttachmentData.push(newData)
							setAttachmentData(newAttachmentData)
							setAttachment({})
						} else {
							message.warning('请上传附件示例')
						}
					},
					onChange: setEditableRowKeys,
					actionRender: (row, config, dom) => [dom.save, dom.cancel],
				}}
			/>
		</div>
	)
}

export default forwardRef(attachmentTable)
